using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Threading;


namespace Bots
{
    /// <summary>
    /// Task manager which make tasks run regular
    /// 
    /// </summary>
    public class ActiveObject 
    {
        private  Queue schedulers = new Queue();
        private  Thread thread = null;
        private  bool exitThread = true;

        public ActiveObject() {
        }

        /// <summary>
        /// add schedule item into queue
        /// </summary>
        /// <param name="c">implement <see cref="ICommand">ICommand</see> interface</param>
        public void AddScheduler(Scheduler c)
        {
            lock (schedulers)
            {
                schedulers.Enqueue(c);
            }
        }

        /// <summary>
        /// start schedule list in current thread
        /// </summary>
        /// <remarks>
        /// </remarks>
        private  void Run()
        {
            while (schedulers.Count != 0)
            {
                Scheduler c = null;

                lock (schedulers)
                {
                    if(schedulers.Count != 0)
                    c = (Scheduler)schedulers.Dequeue();
                }

                if (c != null)
                {
                    c.Run();
                    if (!exitThread)
                    {
                        AddScheduler(c);
                    }
                }
            }
            exitThread = true;
        }

        /// <summary>
        /// stop run
        /// </summary>
        /// <remarks>
        /// clear waitting tasks
        /// </remarks>
        public  void Stop()
        {
            exitThread = true;
        }

        /// <summary>
        /// create new thread run
        /// </summary>
        public  void RunInThread()
        {
            thread = new Thread(new ThreadStart(Run));
            thread.IsBackground = true;
            thread.Priority = ThreadPriority.BelowNormal;

            exitThread = false;
            thread.Start();
        }

        public  bool IsRun()
        {
            return !exitThread;
        }
    }
}
